﻿using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using LimaLims.Application.Service.Base.Dto;
using LimaLims.Application.Service.Basic.Dto;
using LimaLims.Core.Entity.Basic;
using LimaLims.Core;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.EntityFrameworkCore;
using Mapster;
using Furion.DatabaseAccessor.Extensions;
using System.Drawing;
using System.ComponentModel;
using LimaLims.Core.Enum;
using Newtonsoft.Json.Linq;
using System.Reflection;
using Furion.LinqBuilder;
using Microsoft.AspNetCore.Authorization;
using LimaLims.Core.Util;
using Microsoft.CodeAnalysis;

namespace LimaLims.Application.Service.Basic
{
    /// <summary>
    /// 编号规则服务
    /// </summary>
    [ApiDescriptionSettings(Name = "SerialNumberRules", Order = 162)]
    [Route("api")]
    public class SerialNumberRuleService : ISerialNumberRuleService, IDynamicApiController, ITransient
    {
        private readonly IRepository<SerialNumberRules> _serialNumberRulesRep;  // 产品表仓储

        public SerialNumberRuleService(IRepository<SerialNumberRules> serialNumberRulesRep)
        {
            _serialNumberRulesRep = serialNumberRulesRep;
        }

        /// <summary>
        /// 获取业务枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("serialNumberRules/getBusiness")]
        public async Task<List<SelectDto>> GetBusinessEnum()
        {
            var list = new List<SelectDto>();
            var model = default(BusinessType);
            FieldInfo[] fieldinfo = typeof(BusinessType).GetFields();
            foreach (FieldInfo field in fieldinfo)
            {
                SelectDto enumModel = new SelectDto();
                if (!(Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attribute))
                {
                    enumModel.Label = field.GetValue(model).ToString();
                }
                else
                {
                    enumModel.Label = attribute.Description;
                }
                enumModel.Value = field.GetValue(model).GetHashCode();

                if (field.GetValue(model).ToString() != "0")
                {
                    list.Add(enumModel);
                }

            }
            return list;
        }

        /// <summary>
        /// 新增
        /// </summary>
        [HttpPost("serialNumberRules/add")]
        public async Task Add(AddSerialNumberRulesInput input)
        {
            var isExist = await _serialNumberRulesRep.DetachedEntities.AnyAsync(u => u.BusinessType == input.BusinessType);
            if (isExist)
                throw Oops.Oh("已存在相同业务编码规则！");

            var serialNumberRules = input.Adapt<SerialNumberRules>();

            await serialNumberRules.InsertAsync();
        }

        [HttpPost("serialNumberRules/delete")]
        public async Task Delete(long id)
        {
            var serialNumberRules = await _serialNumberRulesRep.FirstOrDefaultAsync(u => u.Id == id);
            if (serialNumberRules == null)
                throw Oops.Oh("不存在此数据");

            await serialNumberRules.DeleteAsync();
        }

        [HttpGet("serialNumberRules/detail")]
        public async Task<SerialNumberRules> Detail(long id)
        {
            var serialNumberRules = await _serialNumberRulesRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (serialNumberRules == null)
                throw Oops.Oh("不存在此数据");

            return serialNumberRules;
        }

        [HttpPost("serialNumberRules/edit")]
        public async Task Edit(EditSerialNumberRulesInput input)
        {
            var serialNumberRules = await _serialNumberRulesRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (serialNumberRules == null)
                throw Oops.Oh("不存在此数据！");

            var isExist = await _serialNumberRulesRep.DetachedEntities.AnyAsync(u => u.BusinessType == input.BusinessType && u.Id != input.Id);
            if (isExist)
                throw Oops.Oh("已存在相同业务编码规则");

            var serialNumberRulesModel = input.Adapt<SerialNumberRules>();

            await serialNumberRulesModel.UpdateAsync();
        }

        [HttpGet("serialNumberRules/page")]
        public async Task<PageResult<SerialNumberRulesOutput>> QueryPage([FromQuery] SerialNumberRulesPageInput input)
        {
            var type = input.Type.HasValue;

            var products = await _serialNumberRulesRep.DetachedEntities
                                         .Where((type, u => u.BusinessType == input.Type))
                                         .OrderBy(u => u.Sort)
                                         .Select(u => new SerialNumberRulesOutput
                                         {
                                             Id = u.Id,
                                             BusinessType = u.BusinessType,
                                             Prefix = u.Prefix,
                                             Digit = u.Digit,
                                             RulesDateType = u.RulesDateType,
                                             RulesText=u.RulesText,
                                             ValidStatus = u.ValidStatus,
                                             Sort=u.Sort,
                                             CreatedTime=u.CreatedTime,
                                             CreatedUserName=u.CreatedUserName,
                                             UpdatedTime=u.UpdatedTime,
                                             UpdatedUserName=u.UpdatedUserName
                                         }).ToADPagedListAsync(input.PageNo, input.PageSize);

            return products;
        }
    }
}
